package smashedapples.google.accounts
{
	import mx.messaging.messages.HTTPRequestMessage;
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	import smashedapples.google.consts.GoogleConsts;
	
	public class GoogleAuthRequest
	{
		public function GoogleAuthRequest( email:String,
										   password:String,
										   service:String,
										   source:String,
										   result:Function,
										   fault:Function = null )
		{
			
			this.email = email;
			this.password = password;
			this.result = result;
			this.source = source;
			this.service = service;
			this.result = result;
			this.fault = fault;
			
		}
		
		public var email:String;
		public var password:String;
		public var result:Function;
		public var fault:Function;
		public var source:String;
		public var service:String;
		
		public function send():AsyncToken
		{
			var params:Object = {};
				params[ "Email" ] = this.email;
				params[ "Passwd" ] = this.password;
				params[ "service" ] = this.service;
				params[ "source" ] = this.source;
				
			var s:HTTPService = new HTTPService();
				s.url =  GoogleConsts.CLIENT_LOGIN_URL;
				s.method = HTTPRequestMessage.POST_METHOD;
				s.addEventListener( ResultEvent.RESULT, resultHandler );
				s.useProxy = false;
				s.resultFormat = "object";
				s.addEventListener( FaultEvent.FAULT, faultHandler );
					
			return s.send( params );
		}
		
		
		private function resultHandler( event:ResultEvent ):void
		{
			var response:GoogleAuthResponse = new GoogleAuthResponse();
				//response.authenticated = true;
				response.parse( event.result as String );
				result( response );  
		}
		
		private function faultHandler( event:FaultEvent ):void
		{
			if( fault != null )
				fault( event );
		}
		
		

	}
}